package com.crm.customers.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.crm.customers.dao.ContractBillDao;
import com.crm.customers.dao.CustomerDao;
import com.crm.customers.model.ContractBill;
import com.crm.customers.model.CustomerInfo;
import com.crm.customers.service.ApproveItemService;
import com.crm.customers.service.ContractBillService;
import com.crm.sys.dao.ApproveConfigureDao;
import com.crm.sys.model.ApproveConfigure;
import com.crm.util.Constants;

@Service("contractBillService")
public class ContractBillServiceImpl implements ContractBillService {
	
	@Autowired
	private ContractBillDao contractBillDao;
	
	@Autowired
	private CustomerDao customerDao;
	
	@Autowired
	private ApproveConfigureDao approveConfigureDao;
	
	@Autowired
	private ApproveItemService approveItemService;
	
	@Override
	public ContractBill insert(ContractBill cb) throws Exception {
		
		/*
		 * 插入发票申请记录，然后呢...
		 * */
		//判断合同是否已经存在
		if (cb.getContractid() == null) {
			cb.setContractid(0L);
		}
		//设置为审批中
		cb.setApprovalstatus(Constants.ApproveState.ONE);
		ContractBill cbl = contractBillDao.insert(cb);
		if (cbl.getId() != null && cbl.getId() > 0) {
			CustomerInfo  customer = customerDao.getCustomerInfoById(cb.getCusid());
			Long urlId = cbl.getId();
			//获取审批流程，插入到审批表
			String approveCode  = Constants.ApproveCode.BILL;
			ApproveConfigure  cig = approveConfigureDao.selectByPrimaryKey(approveCode); 
			approveItemService.saveApprove(cig, cbl.getId(),urlId,cb.getCreateuser(), customer.getCname());
		}
		
		return cbl;
	}

	@Override
	public ContractBill selectBillInfoByParams(ContractBill cb) {
		Long id = cb.getId();
		return contractBillDao.selectByPrimaryKey(id);
	}

	@Override
	public int updataContractBillApproveState(ContractBill cb) {
		return contractBillDao.updataContractBillApproveState(cb);
	}

}
